#!/bin/bash

set -e

echo "🚀 【危险】初始化 Frappe 开发环境，会清空当前文件下的 frappe-bench..."

# 检查是否已经初始化
if [ -f "frappe-bench/sites/dev.localhost/site_config.json" ]; then
    echo "✅ Bench 已经初始化"
    echo ""
    echo "启动服务："
    docker compose down 2>/dev/null || true
    docker compose up -d
    echo ""
    echo "访问地址: http://localhost:8000"
    echo "用户名: Administrator"
    echo "密码: admin"
    exit 0
fi

if [ -d "frappe-bench" ]; then
    echo "🗑️  清理旧环境..."
    docker compose down -v 2>/dev/null || true
    rm -rf frappe-bench
    sed -i 's/command: sleep.*/command: sleep infinity/' docker-compose.yml
fi

mkdir -p frappe-bench


# 启动服务
## 需要把 bench 的 command 临时改成 sleep infinity，以便可以执行以下 bench init 的操作！！！！
echo "🐳 启动服务..."
docker compose up -d

echo "⏳ 等待数据库启动..."
sleep 10

# 1. 初始化: bench init（在临时目录）
echo "📦 初始化 Frappe bench（这需要几分钟）..."
# docker compose exec bench-init bash -c "bench init --skip-redis-config-generation --frappe-branch version-15 ~/frappe-bench/frappe-bench"
docker compose exec bench-init bash -c "
    bench init --skip-redis-config-generation --frappe-branch version-15 /tmp/frappe-bench &&
    echo '----==== slow copying to the mounted external host directory ====----' &&
    mv /tmp/frappe-bench/* /home/frappe/frappe-bench/
"


# 2. 部署：frappe App 和环境
echo "🔧 安装 frappe app 及相关环境..."
docker compose exec bench-init bash -c "
    cd ~/frappe-bench && 
    ~/frappe-bench/env/bin/python -m pip install --quiet --upgrade -e ~/frappe-bench/apps/frappe &&
    bench build
"

# 3. 配置： sites/common_site_config.json
echo "⚙️  配置数据库和 Redis..."
docker compose exec bench-init bash -c 'cat > ~/frappe-bench/sites/common_site_config.json << EOF
{
 "db_host": "db",
 "db_port": 3306,
 "redis_cache": "redis://redis-cache:6379",
 "redis_queue": "redis://redis-queue:6379",
 "redis_socketio": "redis://redis-queue:6379"
}
EOF'

# 4. 创建站点: bench new-site
echo "🌐 创建站点 dev.localhost..."
docker compose exec bench-init bash -c "
    cd ~/frappe-bench &&
    bench new-site dev.localhost \
        --admin-password admin \
        --db-root-password admin \
        --mariadb-user-host-login-scope='%'
"

# 5. 默认站点: bench use (for Nginx)
docker compose exec bench-init bash -c 'bench use dev.localhost'


# # 清理：收尾，调整 docker-compose.yml 为正常启动模式
docker compose stop bench-init
docker compose up -d --force-recreate backend
echo "📝 更新配置..."
sed -i.bak 's/command: sleep infinity/command: sleep 1000/' docker-compose.yml
rm -f docker-compose.yml.bak
# # 重启服务
# echo "🔄 重启服务..."
# docker compose down
# docker compose up -d

echo ""
echo "✅ Frappe 环境初始化完成！"
echo ""
echo "访问地址: http://localhost:8000"
echo "用户名: Administrator"
echo "密码: admin"
echo ""
echo "查看日志: docker compose logs -f backend"
